package demo.huodongbaoming.controller;

import demo.huodongbaoming.service.LoadBalancerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 负载均衡RestTemplate测试控制器
 */
@RestController
@RequestMapping("/api/lb-rest")
public class LoadBalancedRestController {

    @Autowired
    private LoadBalancerService loadBalancerService;
    
    /**
     * 使用负载均衡的RestTemplate调用服务
     * @param serviceId 服务ID
     * @param path API路径
     * @return 服务响应
     */
    @GetMapping("/call/{serviceId}")
    public Map<String, Object> callService(@PathVariable String serviceId, String path) {
        if (path == null || path.isEmpty()) {
            path = "/api/health"; // 默认调用健康检查API
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("service", serviceId);
        result.put("path", path);
        result.put("response", loadBalancerService.callServiceWithLoadBalancer(serviceId, path));
        result.put("timestamp", System.currentTimeMillis());
        
        return result;
    }
    
    /**
     * 测试负载均衡 - 多次调用，展示负载均衡效果
     * @param serviceId 服务ID
     * @param count 调用次数
     * @return 多次调用的结果
     */
    @GetMapping("/test/{serviceId}/{count}")
    public Map<String, Object> testLoadBalancer(@PathVariable String serviceId, @PathVariable int count) {
        String path = "/api/health";
        List<Map<String, Object>> responses = new ArrayList<>();
        
        for (int i = 0; i < count; i++) {
            Map<String, Object> response = loadBalancerService.callServiceWithLoadBalancer(serviceId, path);
            response.put("callNumber", i + 1);
            responses.add(response);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("service", serviceId);
        result.put("path", path);
        result.put("totalCalls", count);
        result.put("responses", responses);
        
        return result;
    }
    
    /**
     * 使用普通RestTemplate调用具体URL
     * @param url 完整URL
     * @return 服务响应
     */
    @GetMapping("/direct")
    public Map<String, Object> callDirectUrl(String url) {
        if (url == null || url.isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "URL参数不能为空");
            return error;
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("url", url);
        result.put("response", loadBalancerService.callServiceWithUrl(url));
        result.put("timestamp", System.currentTimeMillis());
        
        return result;
    }
} 